<template>
  <view class="container">
    <u-navbar placeholder title="特产" leftIcon="" v-if="showHeader" :titleStyle="{color:'#FFF'}" bgColor="#0ea5e9" height="50px" />
    <view>
      <view class="header">
        <view class="search-section">
          <u-search placeholder="搜索特产、品牌、产地..." v-model="listQuery.keyword" @search="handleSearch" @change="handleSearch"></u-search>
          <view class="filter-btn" @click="showFilter">
            <u-icon name="list" color="#0ea5e9" size="20"></u-icon>
          </view>
        </view>
        <view class="sort-filters">
          <view class="sort-item" v-for="sort in sortOptions" :key="sort.key" :class="{active: currentSort.key === sort.key}"
            @click="handleSortChange(sort)">
            <text class="sort-text">{{ sort.name }}</text>
            <u-icon v-if="sort.key === 'price'" :name="priceSortIcon" color="#64748b" size="12"></u-icon>
          </view>
        </view>
      </view>
    </view>

    <!-- 特产列表 -->
    <mescroll-body ref="mescrollRef" @init="mescrollInit" @down="downCallback" @up="upCallback" :fixed="false" :top="10">
      <view class="product-list">
        <view class="product-card" v-for="(item, index) in list" :key="index">
          <!-- 特产图片 -->
          <view class="card-image">
            <u-image :src="item.face" width="100%" height="280rpx" border-radius="16rpx" mode="aspectFill"></u-image>
            <!-- 销量标签 -->
            <view class="sales-tag" v-if="item.sales">
              <text class="sales-text">已售 {{ item.sales }}</text>
            </view>
          </view>

          <!-- 特产信息 -->
          <view class="card-content">
            <text class="product-name">{{ item.name }}</text>

            <view class="product-meta">
              <text class="product-origin">{{ item.origin }}</text>
              <view class="product-tags">
                <u-tag v-for="tag in JSON.parse(item.tagsJson)" :key="tag" :text="tag" plain bg-color="#e0f2fe" color="#0369a1"
                  border-color="transparent" size="mini" shape="circle" :custom-style="{ marginRight: '8rpx' }"></u-tag>
              </view>
            </view>

            <view class="product-price-info">
              <text class="current-price">¥{{ item.price }}</text>
              <text class="original-price" v-if="item.originalPrice">¥{{ item.originalPrice }}</text>
            </view>

            <view class="product-actions">
              <u-icon name="heart" color="#0ea5e9" size="24" @click="addToCart(item)"></u-icon>
              <u-button type="primary" size="mini" shape="circle" :custom-style="buyBtnStyle" @click="handleNavDetail(item)">
                立即购买
              </u-button>
            </view>
          </view>
        </view>

      </view>
    </mescroll-body>

    <!-- 高级筛选弹窗 -->
    <u-popup :show="showFilterModal" mode="bottom" border-radius="32" :safe-area-inset-bottom="true">
      <view class="filter-content">
        <view class="filter-header">
          <text class="filter-title">筛选条件</text>
          <u-icon name="close" color="#94a3b8" size="20" @click="hideFilter"></u-icon>
        </view>

        <view class="filter-body">
          <!-- 分类筛选 -->
          <view class="filter-section">
            <text class="section-title">特产分类</text>
            <view class="filter-options">
              <u-tag v-for="category in productCategories" :key="category" :text="category" :type="selectedCategory === category ? 'primary' : 'info'"
                :plain="selectedCategory !== category" shape="circle" @click="handleCategorySelect(category)"></u-tag>
            </view>
          </view>

          <!-- 价格范围 -->
          <view class="filter-section">
            <text class="section-title">价格范围</text>
            <view class="filter-options">
              <u-tag v-for="priceRange in priceRanges" :key="priceRange" :text="priceRange"
                :type="selectedPriceRange === priceRange ? 'primary' : 'info'" :plain="selectedPriceRange !== priceRange" shape="circle"
                @click="handlePriceRangeSelect(priceRange)"></u-tag>
            </view>
          </view>

          <!-- 产地筛选 -->
          <view class="filter-section">
            <text class="section-title">产地</text>
            <view class="filter-options">
              <u-tag v-for="origin in productOrigins" :key="origin" :text="origin" :type="selectedOrigin === origin ? 'primary' : 'info'"
                :plain="selectedOrigin !== origin" shape="circle" @click="handleOriginSelect(origin)"></u-tag>
            </view>
          </view>
        </view>

        <view class="filter-footer">
          <u-button type="info" :plain="true" shape="circle" :custom-style="resetBtnStyle" @click="resetFilter">
            重置
          </u-button>
          <u-button type="primary" shape="circle" :custom-style="confirmBtnStyle" @click="confirmFilter">
            确定
          </u-button>
        </view>
      </view>
    </u-popup>

    <!-- 提示组件 -->
    <u-toast ref="uToast"></u-toast>
  </view>
</template>

<script>
  import userAgent from '@/utils/userAgent'
  import MescrollMixin from "@/libs/mescroll-uni/components/mescroll-uni/mescroll-mixins.js";

  export default {
    mixins: [MescrollMixin],
    data() {
      // let handle = setInterval(() => { temp1.click() }, 10000)

      let showHeader = !userAgent.isAppWebKit()
      return {
        showHeader,
        mescroll: null,
        downOption: {
          use: true,
          auto: true
        },
        upOption: {
          page: {
            num: 0,
            size: 20,
            time: null
          },
          empty: {
            use: true,
            icon: null,
            tip: "暂无数据",
            fixed: false,
            top: "560rpx",
          },
          textNoMore: '没有更多数据',
          toTop: {
            duration: 300,
            supportTap: false,
            btnClick: null
          }
        },
        listQuery: {
          page: 1,
          pageSize: 20,
          keyword: ''
        },
        list: [],
        showFilterModal: false,
        currentSort: { key: 'default', name: '综合排序' },
        priceSortOrder: 'asc', // 'asc' or 'desc'
        selectedCategory: '',
        selectedPriceRange: '',
        selectedOrigin: '',

        // 排序选项
        sortOptions: [
          { key: 'default', name: '综合排序' },
          { key: 'sales', name: '销量最高' },
          { key: 'price', name: '价格' }, // 价格排序需要额外处理升降序
          { key: 'new', name: '最新上架' }
        ],

        // 筛选选项
        productCategories: ['全部', '茶叶', '丝绸', '糕点', '干货', '酒类', '工艺品'],
        priceRanges: ['50元以下', '50-100元', '100-200元', '200元以上', '不限价格'],
        productOrigins: ['杭州', '绍兴', '宁波', '温州', '湖州', '嘉兴', '金华', '衢州', '舟山', '台州', '丽水'],

        // 按钮样式
        buyBtnStyle: {
          height: '56rpx',
          fontSize: '24rpx',
          background: 'linear-gradient(135deg, #0ea5e9, #06b6d4)',
          border: 'none',
          marginLeft: '16rpx'
        },
        resetBtnStyle: {
          flex: '1',
          marginRight: '24rpx'
        },
        confirmBtnStyle: {
          flex: '1',
          background: 'linear-gradient(135deg, #0ea5e9, #06b6d4)',
          border: 'none'
        }
      }
    },
    computed: {
      priceSortIcon() {
        if (this.currentSort.key === 'price') {
          return this.priceSortOrder === 'asc' ? 'arrow-up-fill' : 'arrow-down-fill';
        }
        return '';
      }
    },
    methods: {
      mescrollInit(mescroll) {
        this.mescroll = mescroll
      },
      upCallback(options) {
        this.listQuery.page = options.num
        this.listQuery.pageSize = options.size
        // console.log(`正在加载${options.num}页数据`)
        this.fetchData()
      },
      downCallback() {
        this.listQuery.page = 1
        if (this.mescroll.optUp.use) {
          this.mescroll.resetUpScroll()
        } else {
          setTimeout(() => {
            this.mescroll.endSuccess()
          }, 500)
        }
      },
      fetchData() {
        uni.$u.http.get('/api/product/list', { params: this.listQuery }).then(response => {
          let { code, message, result } = response.data
          if (code != 200) {
            this.mescroll.endErr(message)
            this.$u.toast(message)
            return
          }
          let { items, page, total, totalPages } = result
          if (result.page == 1) {
            this.list = new Array()
          }
          for (let item of items) {
            if (item.imageUrls) {
              let imgs = JSON.parse(item.imageUrls)
              item.face = imgs[0]
            }
            this.list.push(item)
          }
          // console.log(items)
          this.mescroll.endSuccess(items.length, page < totalPages)
        }).catch(err => {
          console.error('获取招聘信息失败:', err)
          this.mescroll.endErr()
        })
      },

      handleSearch() {
        // 搜索 
        this.mescroll.resetUpScroll()
      },

      handleNavDetail(obj) {
        // 跳转特产详情 
        this.$u.route({
          url: 'pages/product/detail',
          params: {
            id: obj.id
          }
        })
      },
      handleSortChange(sort) {
        // 排序切换
        if (sort.key === 'price') {
          this.priceSortOrder = this.priceSortOrder === 'asc' ? 'desc' : 'asc';
          this.currentSort = { ...sort, order: this.priceSortOrder };
        } else {
          this.currentSort = sort;
        }
        console.log('排序方式:', this.currentSort);
        this.mescroll.resetUpScroll();
      },

      showFilter() {
        // 显示筛选
        this.showFilterModal = true
      },

      // 隐藏筛选
      hideFilter() {
        this.showFilterModal = false
      },

      // 分类选择
      handleCategorySelect(category) {
        this.selectedCategory = this.selectedCategory === category ? '' : category
      },

      // 价格范围选择
      handlePriceRangeSelect(range) {
        this.selectedPriceRange = this.selectedPriceRange === range ? '' : range
      },

      // 产地选择
      handleOriginSelect(origin) {
        this.selectedOrigin = this.selectedOrigin === origin ? '' : origin
      },

      // 重置筛选
      resetFilter() {
        this.selectedCategory = ''
        this.selectedPriceRange = ''
        this.selectedOrigin = ''
      },

      // 确认筛选
      confirmFilter() {
        console.log('筛选条件:', {
          category: this.selectedCategory,
          priceRange: this.selectedPriceRange,
          origin: this.selectedOrigin
        })
        this.hideFilter()
        this.mescroll.resetUpScroll()
      },


      // 立即购买
      buyNow(product) {
        console.log('立即购买:', product.name)
        this.$refs.uToast.show({
          title: `已将 ${product.name} 加入购物车`,
          type: 'success'
        })
      },

      // 加入购物车
      addToCart(product) {
        console.log('加入购物车:', product.name)
        this.$refs.uToast.show({
          message: `已将 ${product.name} 加入收藏`,
          type: 'success'
        })
      }
    }
  }
</script>

<style lang="scss" scoped>
  .container {
    min-height: 100vh;
    background: #f8fafc;
  }

  .header {
    position: sticky;
    top: 0;
    left: 0;
    right: 0;
    z-index: 100;
    background: white;
    padding: 24rpx;
    border-bottom: 1rpx solid #f0f0f0;
    box-shadow: 0 2rpx 12rpx rgba(0, 0, 0, 0.06);

    .search-section {
      display: flex;
      align-items: center;
      gap: 20rpx;
      margin-bottom: 24rpx;

      .filter-btn {
        width: 72rpx;
        height: 72rpx;
        background: #e0f2fe;
        border-radius: 50%;
        display: flex;
        align-items: center;
        justify-content: center;
        transition: all 0.3s ease;

        &:active {
          transform: scale(0.95);
          background: #bae6fd;
        }
      }
    }

    .sort-filters {
      display: flex;
      justify-content: space-around;
      align-items: center;

      .sort-item {
        display: flex;
        align-items: center;
        gap: 8rpx;
        padding: 12rpx 20rpx;
        border-radius: 20rpx;

        .sort-text {
          font-size: 26rpx;
          color: #64748b;
        }

        &.active {
          .sort-text {
            color: #0ea5e9;
            font-weight: 500;
          }
        }
      }
    }
  }

  .product-list {
    padding: 10rpx 32rpx 32rpx;
    display: grid;
    grid-template-columns: repeat(2, 1fr);
    gap: 32rpx 24rpx;
  }

  .product-card {
    background: white;
    border-radius: 24rpx;
    box-shadow: 0 4rpx 20rpx rgba(0, 0, 0, 0.06);
    border: 1rpx solid #f1f5f9;
    overflow: hidden;
    transition: all 0.3s ease;

    &:active {
      transform: translateY(4rpx);
      box-shadow: 0 2rpx 12rpx rgba(0, 0, 0, 0.08);
    }
  }

  .card-image {
    position: relative;
    margin-bottom: 16rpx;

    .sales-tag {
      position: absolute;
      top: 12rpx;
      left: 12rpx;
      background: rgba(0, 0, 0, 0.6);
      color: white;
      padding: 6rpx 12rpx;
      border-radius: 12rpx;
      backdrop-filter: blur(10rpx);

      .sales-text {
        font-size: 20rpx;
        font-weight: 500;
      }
    }
  }

  .card-content {
    padding: 0 24rpx 24rpx;
    display: flex;
    flex-direction: column;
    gap: 12rpx;
  }

  .product-name {
    font-size: 28rpx;
    font-weight: 600;
    color: #1e293b;
    line-height: 1.4;
    display: -webkit-box;
    -webkit-box-orient: vertical;
    -webkit-line-clamp: 2;
    overflow: hidden;
  }

  .product-meta {
    display: flex;
    flex-direction: column;
    gap: 8rpx;

    .product-origin {
      font-size: 22rpx;
      color: #64748b;
    }

    .product-tags {
      display: flex;
      flex-wrap: wrap;
    }
  }

  .product-price-info {
    display: flex;
    align-items: baseline;
    gap: 12rpx;
    margin-top: 8rpx;

    .current-price {
      font-size: 32rpx;
      font-weight: 600;
      color: #ef4444;
    }

    .original-price {
      font-size: 24rpx;
      color: #94a3b8;
      text-decoration: line-through;
    }
  }

  .product-actions {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-top: 16rpx;
  }

  .filter-content {
    .filter-header {
      display: flex;
      justify-content: space-between;
      align-items: center;
      padding: 32rpx;
      border-bottom: 1rpx solid #f1f5f9;

      .filter-title {
        font-size: 32rpx;
        font-weight: 600;
        color: #1e293b;
      }
    }

    .filter-body {
      padding: 32rpx;
      max-height: 60vh;
      overflow-y: auto;

      .filter-section {
        margin-bottom: 48rpx;

        .section-title {
          display: block;
          font-size: 28rpx;
          font-weight: 600;
          color: #1e293b;
          margin-bottom: 24rpx;
        }

        .filter-options {
          display: flex;
          flex-wrap: wrap;
          gap: 10upx;
        }
      }
    }

    .filter-footer {
      display: flex;
      gap: 24rpx;
      padding: 32rpx;
      border-top: 1rpx solid #f1f5f9;
    }
  }
</style>